package com.gs.SynPatrolRep.activity.palBill;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;
import com.gs.SynPatrolRep.R;
import com.gs.SynPatrolRep.activity.base.BaseFragmentActivity;
import com.gs.SynPatrolRep.adapter.TabLayoutPagerAdapter;
import com.gs.SynPatrolRep.apiresult.ApiResultData;
import com.gs.SynPatrolRep.constant.AllConstants;
import com.gs.SynPatrolRep.constant.EventCode;
import com.gs.SynPatrolRep.control.EditTextDC;
import com.gs.SynPatrolRep.control.ItemText;
import com.gs.SynPatrolRep.control.ToolBarTitle;
import com.gs.SynPatrolRep.db.bean.Event;
import com.gs.SynPatrolRep.db.dto.PalBillApprovalDto;
import com.gs.SynPatrolRep.db.dto.PalBillDto;
import com.gs.SynPatrolRep.dialog.CancelDialog;
import com.gs.SynPatrolRep.dialog.ComboPicDialog;
import com.gs.SynPatrolRep.dialog.LoadingDialogUtils;
import com.gs.SynPatrolRep.fragment.PalBillSiteFragment;
import com.gs.SynPatrolRep.presenter.PalBillSitePresenter;
import com.gs.SynPatrolRep.util.NfcUtils;
import com.gs.SynPatrolRep.util.PermissionUtil;
import com.gs.SynPatrolRep.util.SPUtil;
import com.gs.SynPatrolRep.util.WindowUtil;
import com.gs.SynPatrolRep.view.IPalBillSiteView;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

public class PalBillSiteActivity extends BaseFragmentActivity implements IPalBillSiteView {

    private PalBillSitePresenter mPresenter;
    private List<String> titles;
    private List<Fragment> fragments;
    private String id, billNum;
    private int curPos = 0, curState;
    private ItemText itemNum, itemDescribe, itemPlan, itemUnKnow, itemApproval;

    @Override
    public void initFragment() {
        id = getIntent().getStringExtra(AllConstants.ID);
        curState = getIntent().getIntExtra(AllConstants.WHAT, 0);
        ToolBarTitle toolBarTitle = findViewById(R.id.toolBarTitle);
        toolBarTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v.getId() == R.id.item_back) {
                    setResult(1);
                    finish();
                }
            }
        });
        itemApproval = fd(R.id.item_approval);
        itemUnKnow = fd(R.id.item_un_know);
        titles = new ArrayList<>();
        fragments = new ArrayList<>();
        if (curState == 0) {
            setGone();
            titles.add(getResources().getString(R.string.beInspected));
            titles.add(getResources().getString(R.string.completed));
            for (int i = 0; i < titles.size(); i++) {
                setFragment(i);
            }
        } else {
            itemApproval.setVisibility(View.GONE);
            titles.add(getResources().getString(R.string.inspection_item));
            titles.add(getResources().getString(R.string.event_report1));
            for (int i = 0; i < titles.size(); i++) {
                setFragment(i + 2);
            }
            switch (curState){
                case 1:
                    itemUnKnow.setTitle(R.string.cancel);
                    initBtmBtn();
                    break;
                case 2:
                    setGone();
                    break;
                case 3:
                    itemUnKnow.setTitle(R.string.actual);
                    initBtmBtn();
                    break;
                case 4:
                    itemUnKnow.setTitle(R.string.actual);
                    fd(R.id.ll_btn).setVisibility(View.GONE);
                    break;
                default:
                    setGone();
                    break;
            }
        }
    }

    private void setGone() {
        fd(R.id.ll_btn).setVisibility(View.GONE);
        itemUnKnow.setVisibility(View.GONE);
    }

    private void initBtmBtn() {
        MyOnClickListener onClickListener = new MyOnClickListener();
        fd(R.id.btn_exit).setOnClickListener(onClickListener);
        fd(R.id.btn_pass).setOnClickListener(onClickListener);
    }

    @Override
    protected void event(Event event) {

    }

    private void setFragment(int i) {
        Bundle bundle = new Bundle();
        bundle.putInt(AllConstants.WHAT, i);
        bundle.putString(AllConstants.ID, id);
        PalBillSiteFragment fg = new PalBillSiteFragment();
        fg.setArguments(bundle);
        fragments.add(fg);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(Event event) {
        if (event.getWhat() == EventCode.EVENT_SITE_REFRESH) {
            mPresenter.getData(id);
        }
    }

    class MyOnClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            PalBillApprovalDto bean = new PalBillApprovalDto();
            bean.setId(id);
            if (v.getId() == R.id.btn_exit) {
                new CancelDialog(PalBillSiteActivity.this, R.string.exit_change, billNum, new CancelDialog.IDoneListener() {
                    @Override
                    public void getDoneFromDialog(String remark) {
                        bean.setApprover(0);
                        bean.setRemark(remark);
                        mPresenter.approval(bean);
                    }
                }).show();
            } else {
                bean.setApprover(1);
                mPresenter.approval(bean);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (NfcUtils.mAdapter != null) {
            NfcUtils.mAdapter.enableForegroundDispatch(this, NfcUtils.mPendingIntent, NfcUtils.mIntentFilter, NfcUtils.mTechList);
        }
    }

//    @Override
//    protected void onPause() {
//        super.onPause();
//        if (NfcUtils.mAdapter != null) {
//            NfcUtils.mAdapter.disableForegroundDispatch(this);
//        }
//    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        long id = NfcUtils.readNFCId(intent);
        EventBus.getDefault().post(new Event(id + "", EventCode.EVENT_NFC));
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        WindowUtil.getInstance().setBarBgColor(this, R.color.blue);
        mPresenter = new PalBillSitePresenter();
        mPresenter.attachView(this);
        TabLayout tabList = fd(R.id.tab_list);
        ViewPager vpCarContent = fd(R.id.vp_list);
        TabLayoutPagerAdapter adapter = new TabLayoutPagerAdapter(getSupportFragmentManager(), fragments, titles);
        vpCarContent.setAdapter(adapter);
        tabList.setupWithViewPager(vpCarContent);
        tabList.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                curPos = tab.getPosition();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        OnClickListener onClickListener = new OnClickListener();
        itemNum = fd(R.id.item_num);
        itemDescribe = fd(R.id.item_describe);
        itemPlan = fd(R.id.item_plan);
        EditTextDC etSearch = fd(R.id.et_search);
        etSearch.addTextChangedListener(new TextWatcher());
//        掃描
        fd(R.id.iv_scan).setOnClickListener(onClickListener);
        mPresenter.getData(id);
    }

    @Override
    public void onGetDataSuccess(ApiResultData<PalBillDto> apiResult) {
        if (apiResult.getStatus() != 2000) {
            Toast.makeText(this, apiResult.getMessage(), Toast.LENGTH_LONG).show();
            return;
        }
        PalBillDto data = apiResult.getData();
        if (data == null) {
            Toast.makeText(this, R.string.site_error, Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        billNum = data.getBillNum();
        SPUtil.getInstance().putString(AllConstants.NUM, billNum);
        itemNum.setText(billNum);
        itemDescribe.setText(data.getBillName());
        itemPlan.setText(data.getPlanAt());
        EventBus.getDefault().post(new Event(EventCode.EVENT_SITE_ITEM, data.getSites(), data.getEvents()));
        if (curState == 0) {
            if (data.getApprover() != null) {
                itemApproval.setText(data.getApprover().getName());
            }
        } else if (curState == 1) {
            itemUnKnow.setText(data.getCancelRemark() == null ? "" : data.getCancelRemark());
        } else {
            itemUnKnow.setText(data.getFinishAt() == null ? "" : data.getFinishAt());
        }
    }

    @Override
    public void onGetDataFails(Exception e) {
        Toast.makeText(this, R.string.network_error, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onApprovalSuccess(ApiResultData<Object> apiResult) {
        Toast.makeText(this, apiResult.getMessage(), Toast.LENGTH_LONG).show();
        if (apiResult.getStatus() == 2000) {
            setResult(1);
            finish();
        }
    }

    @Override
    public void onApprovalFails(Exception e) {
        Toast.makeText(this, R.string.network_error, Toast.LENGTH_LONG).show();
    }

    @Override
    public void showLoading() {
        LoadingDialogUtils.getInstance().showLoading(this);
    }

    @Override
    public void hideLoading() {
        LoadingDialogUtils.getInstance().dismiss();
    }

    class TextWatcher implements android.text.TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            EventBus.getDefault().post(new Event(s.toString(), EventCode.EVENT_SITE_SEARCH, curPos));
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }

    class OnClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                // 掃描
                case R.id.iv_scan:
                    if (PermissionUtil.addPermission(PalBillSiteActivity.this,
                            new String[]{Manifest.permission.CAMERA},
                            ComboPicDialog.PIC_CAREMA)) {
                        Intent intent = new Intent(PalBillSiteActivity.this, CaptureActivity.class);
                        startActivityForResult(intent, 1);
                    }
                    break;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (data == null) {
                return;
            }
            Bundle bundle = data.getExtras();
            if (bundle == null) {
                return;
            }
            if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                EventBus.getDefault().post(new Event(bundle.getString(CodeUtils.RESULT_STRING), EventCode.EVENT_SCAN));
            }
        } else if (requestCode == 900) {
            NfcUtils nfcUtils = new NfcUtils(this);
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_inspection_list;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mPresenter != null) {
            mPresenter.detachView();
        }
    }

    @Override
    public void onBackPressed() {
        setResult(1);
        finish();
    }
}